class CustomTypeListModal extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            list: [],
            inputValues: {
                customTypeName: '',
                customTypeCode: '',
                description: '',
                sortName: '',
                sortCode: '',
                sortDescription: ''
            },
            customTests: [],
            customSorts: [],
            sortItems: [],
            isEditSort: false
        };
        this.pageCount = 0;
    }

    componentDidMount() {
        let reg = /^[A-Za-z0-9]+$/;
        let regCode = /^[a-zA-Z_0-9]+$/;
        this.verify = {
            name: function (value) {
                if (value.length < 2) {
                    return '类型名称至少得2个字符!';
                }
            },
            type: function (value) {
                let ret = /^[a-zA-Z-]+$/;
                if (!ret.test(value)) {
                    return '类型Key只能是英文或者横线！';
                }
            }
        };

        this.sortVerify = {
            sortName: function (value) {
                if (value.length < 2) {
                    return '选择名称至少得2个字符!';
                }
            },
            sortCode: function (value) {
                if (value.length < 1) {
                    return '分类编码至少得1个字符!';
                }
                if (!regCode.test(value)) {
                    return '分类编码只能是英文，数字，下划线组成！';
                }
            },
            displayNames: function (value) {
                if (value.length < 1) {
                    return '显示名不能为空!';
                }
            },
            sortValues: function (value) {
                if (value.length < 1) {
                    return '自定义属性不能为空!';
                }
                if (!reg.test(value)) {
                    return '对应值必须是英文或者数字！';
                }
            }
        };
    }

    show() {
        this.refs.table.checkboxValue = [];
        this.refs.table.refresh();
        this.refs.modal_add_custom_type_list.show();
    }

    /* custom functions */
    updateList(page, pageSize) {
        if (this.props.customType) {
            let params = {};
            params.pageSize = pageSize;
            params.page = page;
            params.isPage = true;
            params.type = this.props.customType;
            postJson("/cms/resource/queryCustomTypeList.x", params, (data) => {
                this.pageCount = data.data.size;
                this.setState({
                    list: data.data.list
                });
            })
        }
    }

    search() {
        this.refs.table.refresh();
    }

    btnSubmit() {
        let content = [];
        let appConfigTypes = this.state.appConfigTypes;
        for (let i in appConfigTypes) {
            content.push({
                typeName: appConfigTypes[i].typeName,
                typeKey: appConfigTypes[i].typeKey,
                valueName: this.refs[appConfigTypes[i].typeKey].value ? this.refs[appConfigTypes[i].typeKey].text : '没有配置',
                typeValue: this.refs[appConfigTypes[i].typeKey].value
            });
        }
        this.state.inputValues.content = JSON.stringify(content);
        this.state.inputValues.deviceType = this.refs.deviceType.value;
        postJson("/appConfig/info/saveAppConfigInfo.x", this.state.inputValues, () => {
            layer.msg('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;添加成功', {icon: 6});
            this.refs.table.refresh();
            this.refs.modal_add.close();
        });
    }


    delete(id) {
        layui.layer.confirm('确定要删除该条目?删除之后此条目将无法被选中!', (index) => {
            postJson("/appConfig/info/deleteAppConfigInfo.x", {
                    id: id
                },
                () => {
                    this.refs.table.refresh();
                    layer.msg('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;删除成功', {icon: 6});
                });
            layui.layer.close(index);
        });
    }


    addCustomTypes() {
        if (this.props.callback) {
            this.props.callback(this.refs.table.checkboxValue);
        }
        this.refs.modal_add_custom_type_list.close();
    }

    endCallback() {
        this.setState({
            inputValues: {
                customTypeName: '',
                customTypeCode: '',
                description: ''
            },
            customTests: [],
            customSorts: []
        });
    }

    inputChange(type, value) {
        this.state.inputValues[type] = value;
        this.setState({});
    }

    addCustomTypeListModal(customType) {
        this.refs.modal_add_custom_type_view.show(customType);
    }

    addCustomType(){
        let param = {};
        postJson("/cms/resource/type/saveCustomType.x", $('#form').serialize(), function (data) {
            parent.queryCustomTypeList();
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        });
    }

    customAddPerms() {
        this.state.customTests.push({
            customName: '',
            customKey: ''
        });
        this.setState({});
    }

    customTestInputChange(type, index, value) {
        this.state.customTests[index][type] = value;
        this.setState({});
    }

    addCustomTypeSelectModal(sortInfo) {
        if (sortInfo) {
            this.state.inputValues.sortName = sortInfo.sortName;
            this.state.inputValues.sortCode = sortInfo.sortCode;
            this.state.inputValues.sortDescription = sortInfo.sortDescription ? sortInfo.sortDescription : '';
            this.state.sortItems = sortInfo.options;
            this.state.isEditSort = true;
        } else {
            this.state.isEditSort = false;
        }
        this.setState({}, () => {
            this.refs.modal_add_custom_type_select.show();
        });
    }

    customAddSortItem() {
        this.state.sortItems.push({
            displayName: '',
            sortValue: ''
        });
        this.setState({});
    }

    sortItemInputChange(type, index, value) {
        this.state.sortItems[index][type] = value;
        this.setState({});
    }

    addCustomSort() {
        for (let i in this.state.customSorts) {
            if (this.state.customSorts[i].sortCode === this.state.inputValues.sortCode) {
                this.state.customSorts.splice(i, 1);
                break;
            }
        }

        this.state.customSorts.push({
            sortName: this.state.inputValues.sortName,
            sortCode: this.state.inputValues.sortCode,
            options: this.state.sortItems
        });
        this.setState({}, () => {
            this.refs.modal_add_custom_type_select.close();
        });
    }

    selectEndCallback() {
        this.setState({
            inputValues: {
                sortName: '',
                sortCode: '',
                sortDescription: ''
            },
            sortItems: []
        });
    }

    render() {
        return (<div>
            <Modal
                area={['800px']}
                disableOverFlow={true}
                title="添加配置"
                ref="modal_add_custom_type_list">
                <Form type="pane" style={{width: '780px'}}>
                    <Table ref="table" count={this.pageCount}
                           checkboxRenderCallback={() => {
                               this.setState({})
                           }}
                           checkboxKeyname="custom_type_id"
                           pageOnClick={(page, pageSize) => this.updateList(page, pageSize)}>
                        <colgroup>
                            <col width="70"/>
                            <col width="200"/>
                            <col width="200"/>
                            <col/>
                            <col width="60"/>
                        </colgroup>
                        <thead>
                        <tr>
                            <th>选择</th>
                            <th>类型名称&nbsp;&rarr;&nbsp;
                                <Button size="xs" onClick={() => this.addCustomTypeListModal()}>
                                    添加类型
                                </Button>
                            </th>
                            <th>分类编码</th>
                            <th>描述</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {

                            this.state.list.map((array) => {
                                return <tr>
                                    <td>&nbsp;<TCheckbox data={array} tableRef={this.refs.table}/></td>
                                    <td>{array.custom_type_name}</td>
                                    <td>{array.custom_type_code}</td>
                                    <td>{array.description}</td>
                                    <td>
                                        <SecurityCheck roles="admin">
                                            <Button size="xs"
                                                    onClick={() => this.addCustomTypeListModal(array)}>编辑</Button>
                                            <Button size="xs" btnType="danger"
                                                    onClick={() => this.delete(array.id)}>删除</Button>
                                        </SecurityCheck>
                                    </td>
                                </tr>
                            })
                        }
                        </tbody>
                    </Table>
                    <Button
                        size='sm'
                        onClick={() => this.addCustomTypes()}>确定添加</Button>
                </Form>
            </Modal>

            <Modal
                area={['800px']}
                disableOverFlow={true}
                title="添加配置"
                ref="modal_add_custom_type_view">
                <Form type="pane" size="sm" style={{width: '780px'}}>
                    <Item>
                        <Label>自定义名称</Label>
                        <Input type="text"
                               block={true}
                               value={this.state.inputValues.customTypeName}
                               lay-verify="customTypeName"
                               onChange={(value) => this.inputChange('customTypeName', value)}
                               placeholder="请输入名称"
                        />
                    </Item>
                    <Item>
                        <Label>自定义编码</Label>
                        <Input type="text"
                               block={true}
                               value={this.state.inputValues.customTypeCode}
                               lay-verify="customTypeCode"
                               onChange={(value) => this.inputChange('customTypeCode', value)}
                               placeholder="请输入编码"
                        />
                    </Item>
                    <Item>
                        <Label>描述</Label>
                        <Input type="text"
                               block={true}
                               value={this.state.inputValues.description}
                               lay-verify="description"
                               onChange={(value) => this.inputChange('description', value)}
                               placeholder="请输入描述"
                        />
                    </Item>

                    <Item className="layui-form-text">
                        <Label>自定义内容</Label>
                        <Button size="xs" style={{marginTop: '10px'}}
                                onClick={() => this.customAddPerms()}>添加文本类型</Button>
                        <Button size="xs" style={{marginTop: '10px'}}
                                onClick={() => this.addCustomTypeSelectModal()}>添加选择类型</Button>
                        <Button size="xs" style={{marginTop: '10px', width: '26px'}} btnType="primary"
                                onclick="addTips()"><i
                            className="layui-icon">&#xe607;</i></Button>
                        <hr style={{background: '#00acd6'}}/>
                        {this.state.customSorts.map((array, index) => {
                            return <div>
                                <div style={{float: 'left', marginLeft: '10px'}}>
                                    {array.sortName}：
                                    <div className="layui-inline">
                                        <Select>
                                            {array.options.map((item) => {
                                                return <option value={item.displayName}>{item.sortValue}</option>
                                            })}
                                        </Select>
                                    </div>
                                </div>
                                <Button size="sm"
                                        style={{marginLeft: '10px'}}
                                        onClick={() => this.addCustomTypeSelectModal(array)}>编&nbsp;辑
                                </Button>
                                <Button size="sm"
                                        btnType="danger"
                                        onClick={() => {
                                            this.state.customSorts.splice(index, 1);
                                            this.setState({})
                                        }}>删&nbsp;除
                                </Button>
                                <hr/>
                            </div>
                        })}
                        {this.state.customTests.map((array, index) => {
                            return <div>
                                <div style={{float: 'left'}}>
                                    自定义名：
                                    <div className="layui-inline">
                                        <Input
                                            lay-verify="customNames"
                                            placeholder="请输自定义名"
                                            value={array.customName}
                                            onChange={(value) => this.customTestInputChange('customName', index, value)}/>
                                    </div>
                                </div>
                                <div style={{float: 'left', marginLeft: '10px'}}>
                                    key：
                                    <div className="layui-inline">
                                        <Input
                                            lay-verify="customKeys"
                                            value={array.customKey}
                                            onChange={(value) => this.customTestInputChange('customKey', index, value)}/>
                                    </div>
                                </div>
                                <Button size="sm"
                                        btnType="danger"
                                        style={{marginLeft: '10px'}}
                                        onClick={() => {
                                            this.state.customTests.splice(index, 1);
                                            this.setState({})
                                        }}>删&nbsp;除
                                </Button>
                                <hr/>
                            </div>
                        })
                        }
                    </Item>

                    <Item>
                        <Button formBtn={true}
                                size='sm'
                                btnType='normal'
                                lay-submit="true"
                                onClick={() => this.addCustomType()}>确定添加</Button>
                    </Item>
                </Form>

            </Modal>

            <Modal
                area={['800px']}
                disableOverFlow={true}
                title="添加自定义选项"
                endCallback={() => this.selectEndCallback()}
                ref="modal_add_custom_type_select">
                <Form type="pane"
                      size="sm"
                      style={{width: '780px'}}
                      verify={() => {
                          return this.sortVerify;
                      }}>
                    <Item>
                        <Label>分类名称</Label>
                        <Input type="text"
                               block={true}
                               value={this.state.inputValues.sortName}
                               lay-verify="sortName"
                               onChange={(value) => this.inputChange('sortName', value)}
                               placeholder="请输入名称"
                        />
                    </Item>
                    <Item>
                        <Label>分类编码</Label>
                        <Input type="text"
                               block={true}
                               readOnly={this.state.isEditSort ? 'readonly' : ''}
                               value={this.state.inputValues.sortCode}
                               lay-verify="sortCode"
                               onChange={(value) => this.inputChange('sortCode', value)}
                               placeholder="请输入编码"
                        />
                    </Item>
                    <Item>
                        <Label>描述</Label>
                        <Input type="text"
                               block={true}
                               value={this.state.inputValues.sortDescription}
                               lay-verify="sortDescription"
                               onChange={(value) => this.inputChange('sortDescription', value)}
                               placeholder="请输入描述"
                        />
                    </Item>

                    <Item className="layui-form-text">
                        <Label>自定义条目&nbsp;&rarr;&nbsp;
                            <Button size="xs"
                                    onClick={() => this.customAddSortItem()}>添加条目</Button>
                        </Label>
                        <hr style={{background: '#00acd6'}}/>
                        {this.state.sortItems.map((array, index) => {
                            return <div>
                                <div style={{float: 'left'}}>
                                    显示名：
                                    <div className="layui-inline">
                                        <Input
                                            lay-verify="displayNames"
                                            placeholder="请输自定义名"
                                            value={array.displayName}
                                            onChange={(value) => this.sortItemInputChange('displayName', index, value)}/>
                                    </div>
                                </div>
                                <div style={{float: 'left', marginLeft: '10px'}}>
                                    对应值：
                                    <div className="layui-inline">
                                        <Input
                                            lay-verify="sortValues"
                                            value={array.sortValue}
                                            onChange={(value) => this.sortItemInputChange('sortValue', index, value)}/>
                                    </div>
                                </div>
                                <Button size="sm"
                                        btnType="danger"
                                        style={{marginLeft: '10px'}}
                                        onClick={() => {
                                            this.state.sortItems.splice(index, 1);
                                            this.setState({})
                                        }}>删&nbsp;除
                                </Button>
                                <hr/>
                            </div>
                        })}
                    </Item>

                    <Item>
                        <Button formBtn={true}
                                size='sm'
                                btnType='normal'
                                lay-submit="true"
                                onClick={() => this.addCustomSort()}>确定添加</Button>
                    </Item>
                </Form>

            </Modal>
        </div>)
    }
}
